<template>
  <!--  全部任务-->
  <div class="app-container">
    <!-- 工具栏 -->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input
          v-model="query.businessKey"
          size="small"
          clearable
          placeholder="输入申请单号"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleQuery"
        />
        <el-input
          v-model="query.name"
          size="small"
          clearable
          placeholder="输入流程名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleQuery"
        />
        <el-date-picker
          v-model="timeValue"
          class="filter-item"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
        <el-button
          size="small"
          type="primary"
          class="filter-item"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button
          size="small"
          class="filter-item"
          @click="resetQuery"
        >
          重置
        </el-button>
      </div>
    </div>

    <!-- 流程图弹窗 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="showDialog"
      title="流程进度"
      width="1000px"
    >
      <img :src="blowimg" width="1000px" alt="流程进度图">
    </el-dialog>

    <!-- 审批记录抽屉 -->
    <el-drawer
      :title="taskName"
      :visible.sync="showDialog1"
      direction="rtl"
      size="50%"
    >
      <el-timeline style="padding: 0px 15px;">
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          color="#0bbd87"
          size="normal"
          placement="top"
          :timestamp="activity.startTime"
        >
          <el-card style="padding: 0 20px;">
            <p>{{ activity.assignee + '--' + activity.taskName }}</p>
            <p v-if="activity.comment">审批意见：{{ JSON.parse(activity.comment).approvalResion }}</p>
            <p v-if="activity.comment">审批结果：{{ JSON.parse(activity.comment).approvalResult }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>
    <div slot="header" class="clearfix">
      <span class="role-span">全部任务列表</span>
    </div>
    <el-table
      ref="table"
      highlight-current-row
      style="width: 100%;margin-top: 10px"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column
        :selectable="checkboxT"
        type="selection"
        width="55"
      />
      <el-table-column
        prop="businessKey"
        label="申请单号"
      >
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="点击查看详情"
            placement="top"
          >
            <!-- 添加可点击样式 -->
            <span
              style="color: #409EFF; cursor: pointer; text-decoration: underline;"
              @click="handleViewDetails(scope.row)"
            >
              {{ scope.row.businessKey }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="流程名称"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        width="135px"
        label="审批状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.ended == true">审批完成</el-tag>
          <el-tag v-else type="info">审批中</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"

        label="当前审批人"
      >
        <template slot-scope="scope">
          <span v-if=" scope.row.assignee">{{ scope.row.assignee }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="candidateGroup"
        label="审批候选组"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.candidateGroup">{{ scope.row.candidateGroup }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"

        label="审批节点"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.currentTask">{{ scope.row.currentTask }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"

        prop="startUserId"
        label="申请人"
      />
      <el-table-column
        :show-overflow-tooltip="true"

        prop="startTime"
        label="申请时间"
      />
      <el-table-column
        label="操作"
        width="260px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-document"
            @click="getLCById1(scope.row)"
          >
            审批记录
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-picture"
            @click="getLCById(scope.row.processInstanceId)"
          >
            流程图
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :total-num="total" :current-page="currentPage" @handleCurrentChange="handleCurrentPageChange" @handlePageSizeChange="handlePageSizeChange" />
    <ZybmInfoDialog ref="detailsDialog" />
    <!--  责任撤销对话框  -->
    <sjzrDialog ref="sjzrDialogRef" />
    <!-- 数据需求申请对话框 -->
    <sjxqsqDialog ref="sjxqsqDialogRef" />
    <!-- 需求督办申请对话框-->
    <xqdbsqDialog ref="xqdbsqDialogRef" />
  </div>
</template>

<script>
import Pagination from '@/components/common/Pagination.vue'
import ZybmInfoDialog from './ZybmInfoDialog.vue'
// 引入接口请求模块（预留）
import {
  getAllTask,
  getTraceProcess,
  getHistory,
  getCatalogDetail,
  getInteractDetail,
  getSupervisionDetail,
  getDetailBySpbh
} from '@/api/taskManagement/allTasksInfo'
import sjzrDialog from '@/views/TaskManagement/ApprovalRecords/sjzrDialog.vue'
import sjxqsqDialog from '@/views/TaskManagement/ApprovalRecords/sjxqsqDialog.vue'
import xqdbsqDialog from '@/views/TaskManagement/ApprovalRecords/xqdbsqDialog.vue'

export default {
  name: 'ApprovalRecords',
  components: { xqdbsqDialog, sjxqsqDialog, sjzrDialog, ZybmInfoDialog, Pagination },
  data() {
    return {
      timeValue: [],
      // 表格数据
      tableData: [],
      // 分页参数
      total: 0,
      pageSize: 10,
      currentPage: 1,

      // 查询条件
      query: {
        businessKey: '',
        name: ''
      },

      // 弹窗相关
      blowimg: '',
      showDialog: false,
      showDialog1: false,
      activities: [],
      currentId: 0,
      taskName: '',
      selectedRows: []
    }
  },
  created() {
    // 初始化表格数据
    this.loadTableData()
  },
  methods: {
    // 处理查看编目详情点击事件
    handleViewDetails(row) {
      console.log(row, 'row')
      if (row.name === '编目上线申请' || row.name === '编目下线申请' || row.name === '编目使用申请') {
        getCatalogDetail(row.businessKey).then(res => {
          console.log(res, '详情')
          this.$refs.detailsDialog.setDetailData(res)
        })
      } else if (row.name === '责任撤销申请') {
        getDetailBySpbh(row.businessKey).then(res => {
          console.log(res, '责任撤销申请')
          this.$refs.sjzrDialogRef.setDetailData(res)
        })
      } else if (row.name === '数据需求申请') {
        getInteractDetail(row.businessKey).then(res => {
          console.log(res, '数据需求申请')
          this.$refs.sjxqsqDialogRef.setDetailData(res)
        })
      } else if (row.name === '需求督办申请') {
        getSupervisionDetail(row.businessKey).then(res => {
          console.log(res, '需求督办申请')
          this.$refs.xqdbsqDialogRef.setDetailData(res)
        })
      }
    },
    /**
     * 加载表格数据
     * 预留接口调用位置
     */
    loadTableData() {
      getAllTask({
        page: this.currentPage,
        size: this.pageSize,
        businessKey: this.query.businessKey || null,
        name: this.query.name,
        startTime: this.timeValue ? this.timeValue[0] : null,
        endTime: this.timeValue ? this.timeValue[1] : null
      }).then(response => {
        console.log(response, '列表')
        this.tableData = response.content
        this.total = response.totalElements
      }).catch(error => {
        console.error('获取任务列表失败:', error)
      })
    },

    /**
     * 处理查询
     */
    handleQuery() {
      if (this.query.startTime && this.query.endTime && this.query.startTime > this.query.endTime) {
        this.$message.warning('结束时间不能早于开始时间')
        return
      }
      this.currentPage = 1
      this.loadTableData()
    },

    /**
     * 重置查询条件
     */
    resetQuery() {
      this.query = {
        businessKey: '',
        name: '',
        startTime: '',
        endTime: ''
      }
      this.timeValue = null
      this.handleQuery()
    },

    /**
     * 切换分页
     */
    handleCurrentPageChange(page) {
      this.currentPage = page
      this.loadTableData()
    },

    handlePageSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadTableData()
    },

    /**
     * 处理行点击
     */
    handleCurrentChange(val) {
      if (val) {
        this.currentId = val.id
      }
    },

    /**
     * 处理选择变化
     */
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    /**
     * 获取流程图
     * 预留接口调用位置
     */
    getLCById(processInstanceId) {
      // 【接口调用预留点2：获取流程图】
      // 实际使用时替换为：
      getTraceProcess(processInstanceId).then(res => {
        const blob = new Blob([res], { type: 'image/png' })
        const imageUrl = URL.createObjectURL(blob)
        this.blowimg = imageUrl
        this.showDialog = true
      })
        .catch(error => {
          console.error('获取流程图失败:', error)
        })
    },

    /**
     * 获取审批记录
     * 预留接口调用位置
     */
    getLCById1(task) {
      // 【接口调用预留点3：获取审批历史】
      // 实际使用时替换为：
      getHistory(
        task.processInstanceId,
        {
          page: 0,
          size: 999
        }).then(response => {
        console.log(response, 'response123')
        this.activities = response.content
        this.showDialog1 = true
        this.taskName = task.name
      }).catch(error => {
        console.error('获取审批记录失败:', error)
      })

      // 模拟审批记录（实际项目中删除）
      // this.activities = [
      //   {
      //     startTime: task.startTime,
      //     assignee: task.startUserId,
      //     taskName: '发起申请',
      //     comment: JSON.stringify({ yijian: '请审批', checkYorN: '同意' })
      //   },
      //   {
      //     startTime: '2023-10-02 10:15:00',
      //     assignee: '部门经理',
      //     taskName: '部门审核',
      //     comment: JSON.stringify({ yijian: '同意申请', checkYorN: '同意' })
      //   },
      //   {
      //     startTime: '2023-10-03 14:30:00',
      //     assignee: task.assignee,
      //     taskName: task.currentTask,
      //     comment: task.ended ? JSON.stringify({ yijian: '最终审批通过', checkYorN: '同意' }) : ''
      //   }
      // ]
      // this.showDialog1 = true
      // this.taskName = task.name
    },

    /**
     * 选择框权限控制
     */
    checkboxT(row) {
      return true // 可根据实际需求添加权限控制逻辑
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-item {
  margin-right: 10px;
}

.date-item {
  margin-right: 10px;
  width: 240px;
}

.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-card__body {
  padding: 0 10px;
}

::v-deep .el-timeline-item__timestamp {
  font-size: 12px;
}

::v-deep.el-card {
  background-color: white; /* 设置卡片背景色为白色 */
  border: 1px solid #e9ecef; /* 添加浅灰色边框 */
  border-radius: 5px; /* 卡片添加圆角效果 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); /* 增加轻微阴影效果 */
  margin-bottom: 10px; /* 卡片之间添加间距 */
}

::v-deep.el-card p {
  margin: 20px 0; /* 段落上下添加间距 */
  font-size: 14px; /* 调整字体大小 */
  color: #333; /* 调整字体颜色 */
}
</style>

